import axios from 'axios';
import { ElLoading, ElMessage } from 'element-plus'
import { buildUrl, baseUrl } from '@/config'
import Cookies from 'js-cookie';

// 创建 Axios 实例
const instance = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '/' : baseUrl,
  timeout: 50000,
});

// 请求拦截器
instance.interceptors.request.use(config => {
  // 显示加载动画
  // console.log('@token',Cookies);
  startLoading();
  // 添加 token 到请求头
  if (localStorage.eleToken) {
    config.headers.Authorization = 'Bearer ' + localStorage.eleToken;
  }

  return config;
}, error => {
     //获取错误状态码
    const { status } = error.response;
    // 401跳转登录页面
    if (status == 401) {
        ElMessage.error('Token失效，请重新登录！');
        // 清除过期token
        localStorage.removeItem('eleToken');
        // 跳转登录页面
        router.push("/login");
    } else {
        ElMessage.error(error.response.data);
    }
    ElMessage.error(error.response.data);
  return Promise.reject(error)
});

// 响应拦截器
instance.interceptors.response.use(response => {
  // 隐藏加载动画
  endLoading();

  return response;
}, error => {
  endLoading();

  // 显示错误信息
  ElMessage.error(error.response.data);

  return Promise.reject(error);
});

// 加载动画函数
let loading;
const startLoading = () => {
  loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0,0,0,0.7)'
  });
};
const endLoading = () => {
  loading.close();
};

// 统一的请求函数
const sendRequest = (method, url, data = {}, config = {}) => {
  return instance({
    method: method,
    url: url,
    data: data,
    ...config
  }).then(response => {
    return response;
  });
};

// 导出请求函数
export const getRequest = (url, params, config) => {
  return sendRequest('get', url, params, config);
};

export const postRequest = (url, data, config) => {
  return sendRequest('post', url, data, config);
};

export const deleteRequest = (url, data, config) => {
  return sendRequest('delete', url, data, config);
};
